<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- 搜索 -->
      <el-input v-model="query.value" clearable placeholder="输入搜索内容" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" />
      <el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px">
        <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="userType" clearable placeholder="用户来源" class="filter-item" style="width: 130px">
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <el-select v-model="paramsBin.level" clearable placeholder="用户等级" class="filter-item" style="width: 130px">
        <el-option :label="starName(p)" :value="p" v-for="p in 4">
          <template>
            {{starName(p)}} <i v-for="i in p" class="el-icon-star-on" :class="'level'+i"></i>
          </template>
        </el-option>
      </el-select>

      <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
      <!-- 新增 -->
      <el-button
        type="danger"
        class="filter-item"
        size="mini"
        icon="el-icon-refresh"
        @click="toQuery"
      >刷新</el-button>
      <el-button
        class="filter-item"
        size="mini"
        icon="el-icon-download"
        @click="showUploadBox"
      >导入</el-button>

      <el-link type="info" @click="downTemplate" style="margin-left: 10px"  icon="el-icon-info">模板下载</el-link>
    </div>
    <!--表单组件-->
    <eForm ref="form" :is-add="isAdd" />
    <pForm ref="formp" :is-add="isAdd" />
    <detail ref="formd" />
    <!--表格渲染-->
    <el-table v-loading="loading" :data="data" size="small" style="width: 100%;">
      <el-table-column prop="uid" label="用户id" />
      <el-table-column prop="nickname" label="用户昵称" />
      <el-table-column ref="table" prop="avatar" label="用户头像">
        <template slot-scope="scope">
          <a :href="scope.row.avatar" style="color: #42b983" target="_blank"><img :src="scope.row.avatar" alt="点击打开" class="el-avatar"></a>
        </template>
      </el-table-column>
      <el-table-column prop="realName" label="真实姓名" />
      <el-table-column prop="phone" label="手机号码" />
      <el-table-column prop="level" label="用户等级" >
        <template #default="scope">
          <div>
            <i v-for="i in scope.row.level" :class="'level'+i" class="el-icon-star-on"></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="nowMoney" label="用户余额" />
      <el-table-column prop="brokeragePrice" label="佣金金额" />
      <el-table-column prop="integral" label="用户积分" />
      <el-table-column  prop="createTime" label="创建日期" width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <div @click="onStatus(scope.row.uid,scope.row.status)">
            <el-tag v-if="scope.row.status == 1" style="cursor: pointer" :type="''">正常</el-tag>
            <el-tag v-else style="cursor: pointer" :type=" 'info' ">禁用</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用户来源" align="center">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.userType == 'wechat'">公众号</el-tag>
            <el-tag v-else-if="scope.row.userType == 'routine'">小程序</el-tag>
            <el-tag v-else>H5</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="spreadUid" label="推荐人" />
      <el-table-column prop="payCount" label="购买次数" />
      <el-table-column v-if="checkPermission(['admin','YXUSER_ALL','YXUSER_EDIT','YXUSER_DELETE'])" label="操作" width="215" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-permission="['admin','YXUSER_ALL','YXUSER_EDIT']"
            size="mini"
            type="danger"
            @click="editD(scope.row)"
          >查看下级</el-button>
          <el-dropdown size="mini" split-button type="primary" trigger="click">
            操作
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  v-permission="['admin','YXUSER_ALL','YXUSER_EDIT']"
                  size="mini"
                  type="primary"
                  @click="edit(scope.row)"
                >修改用户</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  v-permission="['admin','YXUSER_ALL','YXUSER_EDIT']"
                  size="mini"
                  type="primary"
                  @click="editP(scope.row)"
                >修改余额</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="文件上传"
      :visible.sync="dialogVisible"
      width="400px"
    >
      <el-upload
        class="upload-demo"
        drag
        :before-upload="beforeUpload"
        :headers="headers"
        :action="uplpadAction+'?name='+filename"
        :on-success="handleSuccess"
        :on-error="handleError"
        accept=".xlsx"
        multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传.xlsx文件，且不超过100MB</div>
      </el-upload>

    </el-dialog>

    <!--分页组件-->
    <el-pagination
      :total="total"
      :current-page="page + 1"
      style="margin-top: 8px;"
      layout="total, prev, pager, next, sizes"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import initData from '@/mixins/crud'
import { del, onStatus,execlIn } from '@/api/yxUser'
import eForm from './form'
import pForm from './formp'
import detail from './detail'
import { formatTime } from '@/utils/index'
import {mapGetters} from "vuex";
import { getToken } from '@/utils/auth'

export default {
  components: { eForm, pForm, detail },
  mixins: [initData],
  data() {
    return {
      paramsBin:{
        level: "",
      },
      uploadResult:{},
      dialogVisible:false,
      delLoading: false,
      filename:'',
      userType: '',
      uplpadAction:"",
      headers: {
        'Authorization': getToken()
      },
      queryTypeOptions: [
        { key: 'nickname', display_name: '用户昵称' },
        { key: 'phone', display_name: '手机号码' }
      ],
      statusOptions: [
        { value: 'routine', label: '小程序' },
        { value: 'wechat', label: '公众号' },
        { value: 'H5', label: 'H5' }
      ]
    }
  },
  created() {
    this.uplpadAction=this.fileUploadApi
    //本机调试
    // this.uplpadAction=this.fileUploadApi.replace(this.baseApi,   window.location.origin);
    console.log(this.uplpadAction);
    this.$nextTick(() => {
      this.init()
    })
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  methods: {
    formatTime,
    checkPermission,

    starName(p){
      try{
        let arr=["一","二","三","四"];
        return arr[p-1]+"星";
      }catch (e){
        return "";
      }

    },
    handleSuccess(response, file, fileList) {
      this.$message.success("上传成功");
      this.uploadResult=response;
      execlIn(response).then(e=>{
        this.$message.success(`本次数据:${e.allNum}条 成功导入${e.successNum}条`)
        this.dialogVisible=false;
        this.init();
      })
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      //const msg = JSON.parse(e.message)
      this.$message.error(e.message||"上传失败")
    },
    beforeUpload(file) {
      this.filename=file.name
      if(!file.name.toLocaleLowerCase().endsWith(".xlsx")){
        this.$message.error('仅支持xlsx文件')
        return ;
      }
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.name = file.name
      return isLt2M
    },
    showUploadBox(){
      this.dialogVisible=true;
    },
    downTemplate(){
      window.location.href='/template.xlsx';
    },
    onStatus(id, status) {
      this.$confirm(`确定进行[${status ? '禁用' : '开启'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          onStatus(id, { status: status }).then(({ data }) => {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.init()
              }
            })
          })
        })
        .catch(() => { })
    },
    beforeInit() {
      this.url = 'api/yxUser'
      const sort = 'uid,desc'
      this.params = { page: this.page, size: this.size, sort: sort, userType: this.userType }

      Object.assign(this.params,this.paramsBin);
      const query = this.query
      const type = query.type
      const value = query.value
      if (type && value) { this.params[type] = value }
      return true
    },
    subDelete(uid) {
      this.delLoading = true
      del(uid).then(res => {
        this.delLoading = false
        this.$refs[uid].doClose()
        this.dleChangePage()
        this.init()
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
      }).catch(err => {
        this.delLoading = false
        this.$refs[uid].doClose()
        console.log(err.response.data.message)
      })
    },
    add() {
      this.isAdd = true
      this.$refs.form.dialog = true
    },
    edit(data) {
      this.isAdd = false
      const _this = this.$refs.form
      _this.form = {
        uid: data.uid,
        account: data.account,
        pwd: data.pwd,
        realName: data.realName,
        birthday: data.birthday,
        cardId: data.cardId,
        mark: data.mark,
        partnerId: data.partnerId,
        groupId: data.groupId,
        nickname: data.nickname,
        avatar: data.avatar,
        phone: data.phone,
        addTime: data.addTime,
        addIp: data.addIp,
        lastTime: data.lastTime,
        lastIp: data.lastIp,
        nowMoney: data.nowMoney,
        brokeragePrice: data.brokeragePrice,
        integral: data.integral,
        signNum: data.signNum,
        status: data.status,
        level: data.level,
        spreadUid: data.spreadUid,
        spreadTime: data.spreadTime,
        userType: data.userType,
        isPromoter: data.isPromoter,
        payCount: data.payCount,
        spreadCount: data.spreadCount,
        cleanTime: data.cleanTime,
        addres: data.addres,
        adminid: data.adminid,
        loginType: data.loginType,
        isParkingCoupon:data.isParkingCoupon,
        isDirectionalCoupon:data.isDirectionalCoupon,
      }
      _this.dialog = true
    },
    editP(data) {
      this.isAdd = false
      const _this = this.$refs.formp
      _this.form = {
        uid: data.uid,
        nickname: data.nickname,
        ptype: 1,
        money: 0
      }
      _this.dialog = true
    },
    editD(data) {
      const _this = this.$refs.formd
      _this.form = {
        uid: data.uid,
        nickname: data.nickname
      }
      _this.dialog = true
      _this.spread(data.uid)
    }
  }
}
</script>

<style scoped>
/deep/.el-icon-star-on{
  font-size: 14px;
}
/deep/.level1{
    color: gold;
  }
/deep/.level3{
    color: #ff9100;
  }
/deep/.level2{
    color: #ffc000;
  }
/deep/.level4{
    color: #ff6200;
  }
</style>
